package com.qipay.admin.withdraw.service;

import com.alibaba.fastjson.JSONObject;
import com.hfb.merchant.code.sercret.CertUtil;
import com.qipay.admin.utils.HttpClientUtil;
import com.qipay.scalar.type.BankEnum;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.util.TextUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 代付的逻辑
 */
@Service
public class WithdrawAnotherService {
    private static Logger logger = LoggerFactory.getLogger(WithdrawAnotherService.class);


    private String charset = "utf-8";
    /**
     * 八维码代付，确认通过提现审核，代付（非手动出款）
     * @param cpWithdrawTradlog
     * @param trxType
     * @param agentNo
     * @param accountType
     * @return
     * @throws UnsupportedEncodingException
     */
//    @Transactional
//    public Map<String,Object> pass(CpWithdrawTradlog cpWithdrawTradlog,String trxType,String agentNo,String accountType) throws UnsupportedEncodingException {
//        Map<String, Object> responseMap = anotherApply(cpWithdrawTradlog.getCardNo(),cpWithdrawTradlog.getIdCardNo(),
//                cpWithdrawTradlog.getName(),trxType,agentNo,new BigDecimal(String.valueOf(cpWithdrawTradlog.getActualAmount())).divide(new BigDecimal(String.valueOf("100"))).doubleValue(),
//                accountType,cpWithdrawTradlog.getCardBank(),cpWithdrawTradlog.getIsCompany(),cpWithdrawTradlog.getMobile());
//        return responseMap;
//    }

    /**
     *  八维码代付接口，请求代付（管理员提现）
     * @return
     * @throws UnsupportedEncodingException
     */
    @Transactional
    public Map<String,Object> anotherApply(Map<String, Object> spConfig,String accNo,String accName,String bankCode
            ,String amount) throws UnsupportedEncodingException {
        String df_url = "https://dpos.ttpay.net.cn/rest/v1/api/settle";
        String key = spConfig.get("key").toString();

        Map<String,Object>params = new HashMap<>();
        params.put("Merchant",spConfig.get("Merchant").toString());
        params.put("SecondMerchant","0000");
        params.put("Source","QQ");
        params.put("Serial",System.currentTimeMillis());
        params.put("Amount",1000000);
        params.put("CustBankNo",BankEnum.getCode(bankCode));//"1041000"
        params.put("CustBankAccountNo","6217851700000827401");
        params.put("CustName","付俊");
        params.put("SignType","HMAC");

        String signStr = getParamStr(params);
        String Sign = hamcsha1(signStr.getBytes(),hexStringToBytes(key.toString()));
        params.put("Sign",Sign);
        String result = doJsonPost(df_url.toString(), JSONObject.toJSONString(params));

        Map<String, Object> responseMap = JSONObject.parseObject(result);

        return responseMap;
    }

    /**
     * 合付--查询余额
     * @param
     * @return
     */
    public Map<String, Object> findDfBalance(Map<String, Object> spConfig,String Source){
        String df_url = "https://dpos.ttpay.net.cn/rest/v1/api/Querybalance";
        String Merchant = spConfig.get("Merchant").toString();
        String key = spConfig.get("key").toString();
        Map<String,Object>params = new HashMap<>();
        params.put("Merchant",Merchant);
        params.put("Source",Source);
        params.put("Serial",System.currentTimeMillis());
        params.put("SignType","HMAC");

        String signStr = getParamStr(params);
        String Sign = hamcsha1(signStr.getBytes(),hexStringToBytes(key.toString()));
        params.put("Sign",Sign);
        String result = doJsonPost(df_url.toString(), JSONObject.toJSONString(params));

        JSONObject json = JSONObject.parseObject(result);
        Map<String, Object> responseMap = json;
        return responseMap;
    }

    public String  getParamStr(Map<String , Object> paramMap){
        SortedMap<String, Object> smap = new TreeMap<String, Object>(paramMap);
        StringBuffer stringBuffer = new StringBuffer();
        for (Map.Entry<String, Object> m : smap.entrySet()) {
            Object value = m.getValue();
            if (value != null && StringUtils.isNotBlank(String.valueOf(value))){
                stringBuffer.append(m.getKey()).append("=").append(value).append("&");
            }
        }
        stringBuffer.delete(stringBuffer.length() - 1, stringBuffer.length());
        return stringBuffer.toString();
    }


    public String hamcsha1(byte[] data, byte[] key){
        try {
            SecretKeySpec signingKey = new SecretKeySpec(key, "HmacSHA1");
            Mac mac = Mac.getInstance("HmacSHA1");
            mac.init(signingKey);
            return byte2hex(mac.doFinal(data));
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        }
        return null;
    }

    public String byte2hex(byte[] b)
    {
        StringBuilder hs = new StringBuilder();
        String stmp;
        for (int n = 0; b!=null && n < b.length; n++) {
            stmp = Integer.toHexString(b[n] & 0XFF);
            if (stmp.length() == 1)
                hs.append('0');
            hs.append(stmp);
        }
        return hs.toString().toUpperCase();
    }

    public byte[] hexStringToBytes(String hexString) {
        if (hexString == null || hexString.equals("")) {
            return null;
        }
        hexString = hexString.toUpperCase();
        int length = hexString.length() / 2;
        char[] hexChars = hexString.toCharArray();
        byte[] d = new byte[length];
        for (int i = 0; i < length; i++) {
            int pos = i * 2;
            d[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1]));

        }
        return d;
    }
    private byte charToByte(char c) {
        return (byte) "0123456789ABCDEF".indexOf(c);
    }


    public static String doJsonPost(String urlPath, String Json) {
        // HttpClient 6.0被抛弃了
        String result = "";
        BufferedReader reader = null;
        try {
            URL url = new URL(urlPath);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setUseCaches(false);
            conn.setRequestProperty("Connection", "Keep-Alive");
            conn.setRequestProperty("Charset", "UTF-8");
            // 设置文件类型:
            conn.setRequestProperty("Content-Type","application/json; charset=UTF-8");
            // 设置接收类型否则返回415错误
            //conn.setRequestProperty("accept","*/*")此处为暴力方法设置接受所有类型，以此来防范返回415;
            conn.setRequestProperty("accept","application/json");
            // 往服务器里面发送数据
            if (Json != null && !TextUtils.isEmpty(Json)) {
                byte[] writebytes = Json.getBytes();
                // 设置文件长度
                conn.setRequestProperty("Content-Length", String.valueOf(writebytes.length));
                OutputStream outwritestream = conn.getOutputStream();
                outwritestream.write(Json.getBytes());
                outwritestream.flush();
                outwritestream.close();
            }
            if (conn.getResponseCode() == 200) {
                reader = new BufferedReader(
                        new InputStreamReader(conn.getInputStream()));
                result = reader.readLine();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return result;
    }

}
